<template>
  <div class="container">
    <div class="app-container">
      <div class="left">
        <el-input
          v-model="queryParams.keyword"
          style="margin-bottom: 10px"
          type="text"
          prefix-icon="el-icon-search"
          size="small"
          placeholder="输入员工姓名全员搜索"
          @input="search"
        />
        <!-- 树形组件 -->
        <el-tree
          ref="deptTree"
          :data="depts"
          default-expand-all
          :expand-on-click-node="false"
          :props="defaultProps"
          :highlight-current="true"
          node-key="id"
          @current-change="handleNodeClick"
        />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <!-- //按钮权限 v-permission="'add-yuangong'"   v-permission 是自定义的-main可查-->
          <!-- <el-button
            v-permission="'add-yuangong'"
            size="mini"
            type="primary"
            @click="$router.push('/employee/detail')"
            >添加员工</el-button
          > -->
          <el-button
            size="mini"
            type="primary"
            @click="$router.push('/employee/detail')"
            >添加员工</el-button
          >
          <el-button size="mini" @click="showExcelDialog = true"
            >excel导入</el-button
          >
          <el-button size="mini" @click="exportExcel">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="tableData" style="width: 100%">
          <el-table-column label="头像" prop="staffPhoto">
            <template v-slot="{ row }">
              <el-avatar
                v-if="row.staffPhoto"
                :size="30"
                :src="row.staffPhoto"
              />
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="应聘形式">
            <template v-slot="{ row }">
              <span>{{
                row.formOfEmployment === 1
                  ? '正式'
                  : row.formOfEmployment === 2
                  ? '非正式'
                  : '未知'
              }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作">
            <template v-slot="{ row }">
              <el-button
                type="text"
                size="mini"
                @click="$router.push(`/employee/detail/${row.id}`)"
                >查看</el-button
              >
              <el-button type="text" size="mini" @click="roleDetail(row.id)"
                >角色</el-button
              >
              <el-popconfirm
                title="这是一段内容确定删除吗？"
                @onConfirm="deleteRole(row.id)"
              >
                <el-button
                  slot="reference"
                  type="text"
                  size="mini"
                  style="margin-left: 10px"
                  >删除</el-button
                >
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination
            layout="total,prev, pager, next"
            :total="total"
            :default-page-size="queryParams.pagesize"
            :current-page="queryParams.page"
            @current-change="changePage"
          />
        </el-row>
      </div>
    </div>
    <import-excel
      :show-excel-dialog.sync="showExcelDialog"
      @uploadSuccess="getEmployee"
    />
    <el-dialog :visible.sync="showRoleDialog" title="分配角色">
      <el-checkbox-group v-model="roleIds">
        <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{
          item.name
        }}</el-checkbox>
        <el-row type="flex" justify="center" style="margin-top: 20px">
          <el-button type="primary" size="small" @click="assignRole"
            >确定</el-button
          >
          <el-button size="small" @click="showRoleDialog = false"
            >取消</el-button
          >
        </el-row>
      </el-checkbox-group>
    </el-dialog>
  </div>
</template>

<script>
import { getDepartment } from '@/api/department'
import { getRoleList, assignRole, getEmployeeInfo } from '@/api/employee'
import { transListToTreeData } from '@/utils'
import {
  getEmployeeList,
  exportEmployeeExcel,
  deleteEmployee
} from '@/api/employee'
import FileSaver from 'file-saver'
import ImportExcel from './components/import-excel.vue'
export default {
  name: 'Employee',
  components: {
    ImportExcel
  },
  data() {
    return {
      depts: [],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      // 查询参数
      queryParams: {
        departmentId: null,
        pagesize: 10,
        page: 1,
        keyword: '' // 根据名字模糊查询
      },
      tableData: [],
      total: null,
      showExcelDialog: false, // 控制excel的弹层显示和隐藏
      roleList: [],
      showRoleDialog: false, // 控制角色分配弹层显示和隐藏
      roleIds: [], // 角色关联的权限集合
      currentRoleId: null // 当前选中的角色id
    }
  },
  created() {
    this.getDepartment() // 获取部门列表
    this.getRoleList() // 获取已启用的角色列表
  },
  methods: {
    // 员工表格获取
    async getEmployee() {
      const { rows, total } = await getEmployeeList(this.queryParams)
      this.tableData = rows
      this.total = total
    },
    // 员工管理-左侧树的加载
    async getDepartment() {
      // 调取接口数据
      // 接口数据处理（递归）
      this.depts = transListToTreeData(await getDepartment(), 0)
      this.queryParams.departmentId = this.depts[0].id
      // 树组件渲染是异步的 等到更新完毕
      this.$nextTick(() => {
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      // 加载表格
      this.getEmployee()
    },
    // 节点变化
    handleNodeClick(data) {
      this.queryParams.departmentId = data.id
      this.queryParams.page = 1
      this.getEmployee()
    },
    // 分页切换
    changePage(newPage) {
      this.queryParams.page = newPage
      this.getEmployee()
    },
    search() {
      // 单位时间内只执行最后一次
      // this的实例上赋值了一个timer(su)的属性
      // 清理上一次的定时器
      clearTimeout(this.su)
      this.su = setTimeout(() => {
        this.queryParams.page = 1
        this.getEmployee()
      }, 300)
    },
    // 导出员工表格-Excel
    async exportExcel() {
      // console.log(result) // 使用一个npm包 直接将blob文件下载到本地 file-saver
      // FileSaver.saveAs(blob对象,文件名称)
      const result = await exportEmployeeExcel()
      FileSaver.saveAs(result, '员工表格.xlsx')
    },
    // 删除员工
    async deleteRole(id) {
      await deleteEmployee(id)
      if (this.tableData.length === 1 && this.queryParams.page > 1) {
        this.queryParams.page--
      }
      this.getEmployee()
      this.$message.success('删除员工成功')
    },
    // // 获取-已启用的角色列表
    async getRoleList() {
      this.roleList = await getRoleList()
    },
    // 角色分配 弹窗
    async roleDetail(id) {
      const { roleIds } = await getEmployeeInfo(id)
      this.roleIds = roleIds
      this.currentRoleId = id
      this.showRoleDialog = true
    },
    // 角色分配-保存
    async assignRole() {
      await assignRole({
        roleIds: this.roleIds,
        id: this.currentRoleId
      })
      this.$message.success('分配用户角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;
  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }
  .right {
    flex: 1;
    padding: 20px;
    .opeate-tools {
      margin: 10px;
    }
    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04c9be;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>
